package cn.jsu.oj.judgment.factory;


import cn.jsu.oj.judgment.net.starter.JudgeStarter;
import cn.jsu.oj.judgment.parsing.JudgeStarterAnn;
import cn.jsu.oj.judgment.satellite.util.SpringUtil;
import cn.jsu.oj.judgment.utils.AnnotationPackageScanUtil;
import cn.jsu.oj.judgment.utils.StringUtil;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 判题机启动器工厂
 */
public class JudgeStartFactory implements JudgeFactory{

    private Map<Short, JudgeStarter> judgeStartMap;

    @Override
    public void build() {
        this.judgeStartMap = new ConcurrentHashMap<>();
        List<Class<?>> classList = AnnotationPackageScanUtil.scanPackage("cn", JudgeStarterAnn.class);
        for (Class<?> clazz : classList) {
            Short starterNo = clazz.getAnnotation(JudgeStarterAnn.class).starter();
            String[] strings = clazz.getName().split("\\.");
            String beanName = StringUtil.initialFormat(strings[strings.length - 1], false);
            SpringUtil.registerBean(beanName, clazz, SpringUtil.getBean(clazz) != null);
            this.judgeStartMap.put(starterNo, (JudgeStarter) SpringUtil.getBean(beanName));
        }
    }

    @Override
    public Object getProduct(Short goodsNo) {
        if (goodsNo == 0) {
            return this.judgeStartMap;
        }
        return this.judgeStartMap.get(goodsNo);
    }
}
